
<!--
 * @Author: ljc
 * @Date: 2023-04-25 15:00:24
 * @LastEditors: g05047
 * @LastEditTime: 2023-06-08 20:09:44
 * @Description: 项目手动分配列表
-->
<template>
  <div>
    <rk-dialog width="80%"
      height="70%"
      :title="title"
      :visible="visible"
      :destroyOnClose="true"
      @close="hanldeClose"
      :maskClosable="true">
      <RkContainer :isFooter="false"
        :isAside=false
        :isHeader="false">
        <template #main>
          <RkCenter>
            <template #condition>
              <RkCenter-bar v-show="true">
                <template #content>
                  <el-form ref="form"
                    :inline="true">
                    <span>任务名称：{{ taskName }}</span>
                  </el-form>
                </template>
                <template #buttons>
                </template>
              </RkCenter-bar>
            </template>
            <template #content>
              <rk-grid ref="manualTableRef"
                key="applyId"
                dataUrl="/reviewtask/getAssignProjects"
                boxConfig
                :params="queryParams"
                :columns="tableColumns"
                :pagerConfig='false'
                :keepSource="true">
                <template #toolbar_buttons>
                  <rk-tree-select enum="EXPERT_ASSIGN_STATUS"
                    class="w-200px"
                    style="margin-left: 10px;"
                    :filterable="false"
                    :showCode="false"
                    :clearable="false"
                    v-model="queryParams.type"
                    @change="handleSearch">
                  </rk-tree-select>
                </template>
                <template #toolbar_tools>
                  <el-input v-model="queryParams.keyWords"
                    placeholder="请输入项目名称/项目编码"
                    class="w-200px"
                    style="margin-right: 12px;"
                    clearable
                    @input="handleSearch">
                  </el-input>
                  <template v-if="queryParams.type === 0">
                    <el-button style="margin-right: 12px;"
                      type="primary"
                      @click="handleAdd('multiple')">
                      指派专家
                    </el-button>
                  </template>
                  <template v-if="queryParams.type === 1">
                    <el-button style="margin-right: 12px;"
                      type="danger"
                      @click="handleCancle('撤销')">
                      撤销
                    </el-button>
                  </template>
                </template>
                <template #addOperation="{ row }">
                  <div class="operation-box">
                    <el-button class="button-new-tag ml-1"
                      size="small"
                      @click="handleAdd('single',row)">
                      添加
                    </el-button>
                  </div>
                </template>
                <template #expertOperation="{ row }">
                  <el-tag v-for="item in row.expertList"
                    :key="item.expertId"
                    class="expert-tag"
                    closable
                    :disable-transitions="false"
                    @close="handleRemove(item,row)">
                    {{ item.name }}
                  </el-tag>
                </template>
              </rk-grid>
            </template>
          </RkCenter>
        </template>
      </RkContainer>
      <template #footer>
        <template v-if="queryParams.type === 0">
          <el-button type="primary"
            @click="handleConfirm('分配')">保存</el-button>
          <el-button @click="hanldeClose()">取消</el-button>
        </template>
        <template v-else> <el-button @click="hanldeClose()">取消</el-button></template>
      </template>
    </rk-dialog>
    <project-add-expert-dialog ref="projectAddExpertDialogViewRef"
      @save="handleSave"></project-add-expert-dialog>
  </div>
</template>
<script setup>
import { nextTick, reactive, ref, toRaw } from 'vue';
import ProjectAddExpertDialog from './ProjectAddExpertDialog.vue'
import XEUtils from 'xe-utils';
import { RkConfirmBox } from '@/components/message-box/index.js'
import { useExpertsApi } from '@/api/index'
const { reviewtaskCancelProjects, saveExpertByProject } = useExpertsApi();

const emit = defineEmits(['refresh'])
const { appContext } = getCurrentInstance();
const globalProxy = appContext.config.globalProperties;
const manualTableRef = ref('')
const projectAddExpertDialogViewRef = ref(null)
const taskName = ref(null)
// 查询参数
let queryParams = reactive({
  taskId: undefined,
  keyWords: undefined,
  type: 0,
})
const defaultQueryParams = {
  taskId: undefined,
  keyWords: undefined,
  type: 0,
}
let operationType = ''
let seleRowModel = {}
const visible = ref(false)
const title = ref('手动分配列表')
const tableColumns = reactive([
  {
    field: 'adName', title: '地区名称', width: 250, align: 'left',
  },
  { field: 'agName', title: '单位名称', width: 180, align: 'left', },
  { field: 'proName', title: '项目名称', width: 250, align: 'left', cellRender: { name: 'xmYHS' } },
  { field: 'proCode', title: '项目编码', width: 200, align: 'left', },
  {
    field: 'expertList', title: '已分配评审专家', align: 'left', width: 400, fixed: 'right', showOverflow: false, slots: { default: 'expertOperation' }, className: 'allot-expert'
  },
  {
    field: 'addOpreation', title: '操作', width: 80, align: 'left', fixed: 'right', slots: { default: 'addOperation' }
  },
])
/** 删除 */
const handleRemove = (item, row) => {
  row.expertList.splice(row.expertList.indexOf(item), 1)
}
/** 添加 */
const handleAdd = (type, row) => {
  let params = {}
  operationType = type
  if (type === 'multiple') {
    const seleRows = manualTableRef.value.getCheckboxRecords()
    if (seleRows.length == 0 || !seleRows) {
      globalProxy.$message({ message: `请至少选择一条数据！`, type: "warning" });
      return
    }
    params = {
      taskId: queryParams.taskId,
      applyIds: undefined
    }
    projectAddExpertDialogViewRef.value.handleOpen(params)
  } else if (type === 'single') {
    const seleRow = row
    seleRowModel = seleRow
    let expertIds = undefined
    let expertArray = []
    seleRow.expertList.forEach((item) => {
      expertArray.push(item.expertId)
    })
    expertIds = expertArray.join(',')
    params = {
      taskId: queryParams.taskId,
      applyIds: seleRow.applyId,
      expertIds: expertIds
    }
    projectAddExpertDialogViewRef.value.handleOpen(params)
  }
}
/** 取消撤销 */
const handleCancle = (textName) => {
  const seleRows = manualTableRef.value.getCheckboxRecords()
  if (seleRows.length == 0 || !seleRows) {
    globalProxy.$message({ message: `请至少选择一条数据进行${textName}！`, type: "warning" });
    return
  }
  RkConfirmBox({
    title: '提示',
    content: `您确定要${textName}吗？`,
    onSubmit: async function () {
      //获取选中数据
      const applyIdArray = []
      seleRows.forEach(element => {
        applyIdArray.push(element.applyId)
      });
      const applyIds = applyIdArray.join(',')
      const params = { applyIds, taskId: queryParams.taskId }
      const result = await reviewtaskCancelProjects(params)
      const { data, code, msg } = result
      if (code === 200) {
        globalProxy.$message({ message: `${textName}成功！`, type: "success" });
        handleSearch()
      } else {
        globalProxy.$message({ message: `${msg}`, type: "error" });
      }
    },
    onCancel: function () {
    }
  })
}
/** 保存回调 */
const handleSave = (models) => {
  if (operationType === 'multiple') {
    const seleRows = manualTableRef.value.getCheckboxRecords()
    seleRows.forEach(element => {
      let array = element.expertList
      const expertArray = XEUtils.clone(models, true)
      array = expertArray
      element.expertList = array
    })
    manualTableRef.value.reloadRow(seleRows)
  } else if (operationType === 'single') {
    let array = seleRowModel.expertList
    const expertArray = XEUtils.clone(models, true)
    array = [...array, ...expertArray]
    seleRowModel.expertList = array
    manualTableRef.value.reloadRow(seleRowModel)
  }
}
/** 查询 */
const handleSearch = async () => {
  await nextTick()
  manualTableRef.value.searchEvent()
}
/** 打开弹出层 */
const handleOpen = async (id, name) => {
  visible.value = true
  taskName.value = name
  queryParams = reactive({
    ...defaultQueryParams
  })
  queryParams.taskId = id
}
/** 关闭弹窗 */
const hanldeClose = () => {
  visible.value = false
}
/** 确认提交 */
const handleConfirm = async (textName) => {
  let expertProjectBo = []
  let isVerification = false
  const { tableData } = manualTableRef.value.getTableData()
  if (queryParams.type === 1) {// 已分配
    tableData.forEach(element => {
      let model = {}
      const expertIdArray = []
      model.applyId = element.applyId
      model.taskId = queryParams.taskId
      element.expertList.forEach((item) => {
        expertIdArray.push(item.expertId)
      })
      model.expertIds = expertIdArray.join(',')
      expertProjectBo.push(model)
    })
  } else { // 待分配
    tableData.forEach(element => {
      let model = {}
      const expertIdArray = []
      model.applyId = element.applyId
      model.taskId = queryParams.taskId
      if (element.expertList.length > 0) {
        element.expertList.forEach((item) => {
          expertIdArray.push(item.expertId)
        })
        model.expertIds = expertIdArray.join(',')
        expertProjectBo.push(model)
        isVerification = true
      } else {
        isVerification = false
        return
      }
    })
  }
  if (!isVerification) {
    globalProxy.$message({ message: `已分配评审专家数据不能为空！`, type: "warning" });
    return
  }
  visible.value = false
  const params = expertProjectBo
  const result = await saveExpertByProject(params)
  const { data, code, msg } = result
  if (code === 200) {
    globalProxy.$message({ message: `${textName}成功！`, type: "success" });
    emit('refresh')
    handleSearch()
  } else {
    globalProxy.$message({ message: `${msg}`, type: "error" });
  }
}
// 对外暴露方法
defineExpose({
  handleOpen,
})

</script>
<style lang="scss" scoped>
:deep(.allot-expert) {
  line-height: 30px;
}
.expert-tag {
  margin-right: 5px;
}
.operation-box {
  display: flex;
  justify-content: space-around;
}
.w-200px {
  width: 200px;
}
</style>
    